package controller

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"mypro/controller"
	"mypro/dao/mysql"
	"mypro/models"
	"mypro/service"
)

func Loginhandler(ctx *gin.Context) {
	var p models.LoginRequest
	if err := ctx.ShouldBindJSON(&p); err != nil {
		//判断err是不是validator类型
		_, ok := err.(validator.ValidationErrors)
		if !ok {
			controller.ResponseError(ctx, controller.CodeInvalidParam)
			return
		}
		//controller.ResponseErrorWithMsg(ctx,controller.CodeInvalidParam)
		//controller.ResponseError(ctx)
		//return
	}

	// 2.业务逻辑处理
	user, err := service.Login(&p)
	if err != nil {
		if errors.Is(err, mysql.ErrorUserNotExist) {
			controller.ResponseError(ctx, controller.CodeUserNotExist)
			return
		}
		controller.ResponseError(ctx, controller.CodeInvalidPassword)
		return
	}

	// 3.返回响应
	controller.ResponseSuccess(ctx, gin.H{
		"user_id":   fmt.Sprintf("%d", user.UserID), // id值大于1<<53-1  int64类型的最大值是1<<63-1
		"user_name": user.UserName,
		"token":     user.Token,
	})
}
